import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import Search from 'antd/lib/input/Search';
import { Button, Table, Space, Modal, message, Dropdown, Menu } from 'antd';
import { ColumnsType } from 'antd/es/table/interface';
import { IntentionLibraryInfo } from '../../schema/IntentionLibrary';
import {
  getIntentions,
  deleteIntention,
  downloadBatchList,
  getIntentionsUploadInfo,
  confirmUploadIntention,
  batchUnderstandByVersion,
  getBatchStudyProgressByVersion,
  confirmStudyIntention,
} from '../../servers/servers';
import UploadBatchModal from '../UploadBatchModal';
import { deleteRowChangePageNum, randomNum } from 'utils/tools';

import './style.scss';
import UploadingPic from '../UploadingPic';
import { debounce } from 'lodash';

import { JSONObject } from 'admin/schema/common';
import produce from 'immer';
import { useDispatch, useSelector } from 'react-redux';
import { intentionAction } from 'store/intention';
import moment from 'moment';

/**
 * 意图库
 * 示例：AI管理-机器人管理-版本管理-配置话术流程-意图库
 */
export const IntentionLibrary: React.FC<{ versionId: number }> = props => {
  const history = useHistory();
  const { versionId } = props;
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table数据
  const [intentionList, setIntentionList] = useState<IntentionLibraryInfo[]>([]);

  // 上传弹窗
  const [uploadVisble, setUploadVisble] = useState(false);
  // 导入意图-进度值
  const [progressData, setProgressData] = useState<{
    status: number;
    percent: number;
    errorReason: string;
    type?: string;
  }>();
  // 批量学习意图-进度值
  const [studyProgressData, setStudyProgressData] = useState<{
    status: number;
    percent: number;
    errorReason: string;
    type?: string;
  }>();
  // 页面卸载标志：true-卸载
  const isUnmount = useRef<any>(undefined);
  // 计时器-刷新列表，显示导入进度计时器
  const timer = useRef<any>(undefined);

  /**存储搜索条件 */
  const { searchForm } = useSelector((state: JSONObject) => state.intentionList);
  const dispatch = useDispatch();

  /**
   * 查询上传进度
   */
  const checkUploading = useCallback(async () => {
    try {
      const { data } = await getIntentionsUploadInfo(versionId);
      if (isUnmount.current) {
        console.log('>>>>>>>>>>>页面已经卸载-return >>>>>>>>>>>');
        return;
      }
      console.log('查询进度', data);
      const { importStatus, progressFinishedNumber, progressTotalNumber, errorReason } = data;
      if (!importStatus) {
        // 显示列表页面
        clearTimer();
        setProgressData(undefined);
      } else {
        // 显示插画页面
        if (importStatus === 1 || importStatus === 2) {
          // 进行中
          startTimer('upload');
        } else {
          // 完成或者失败，显示【确认】按钮
          clearTimer();
        }
        let percent = 0;
        percent = Math.floor(
          (progressFinishedNumber && progressTotalNumber
            ? progressFinishedNumber / progressTotalNumber
            : 0) * 100
        );
        const newData = { status: importStatus, percent: percent, errorReason: errorReason || '' };
        setProgressData(newData);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
      // 出现异常，显示列表页面
      setProgressData({ status: 0, percent: 0, errorReason: '' });
      clearTimer();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [versionId]);
  /**
   * 查询学习进度
   */
  const checkBatchStudying = useCallback(async () => {
    try {
      const { data } = await getBatchStudyProgressByVersion(versionId, 'intention');
      if (isUnmount.current) {
        console.log('>>>>>>>>>>>页面已经卸载-return >>>>>>>>>>>');
        return;
      }
      console.log('查询进度', data);
      if (!data) {
        // 显示列表页面
        clearTimer();
        setStudyProgressData(undefined);
      } else {
        // 显示插画页面
        const { isFinish, finishedNumber, totalNumber } = data;
        let studyStatus: number; // 记录状态
        if (!isFinish) {
          // 进行中
          startTimer('study');
          studyStatus = 2;
        } else {
          // 完成显示【确认】按钮
          clearTimer();
          studyStatus = 4;
        }
        // 进度值
        const percent = Math.floor(
          (finishedNumber && totalNumber ? finishedNumber / totalNumber : 0) * 100
        );
        const newData = { status: studyStatus, percent: percent, errorReason: '', type: 'study' };
        setStudyProgressData(newData);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
      // 出现异常，显示列表页面
      setStudyProgressData({ status: 0, percent: 0, errorReason: '', type: 'study' });
      clearTimer();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [versionId]);

  /**
   * Table数据加载
   */
  const getTableData = useCallback(async () => {
    if (progressData || studyProgressData) {
      return;
    }
    setTableLoading(true);
    const { pageNo, pageSize, searchText } = searchForm;
    console.log(searchForm, '查询条件===请求列表接口数据');
    try {
      const { data, count } = await getIntentions({
        pageNo,
        pageSize,
        versionId,
        intentionName: searchText,
      });
      console.log('getTableData -> res', data, count);
      setIntentionList(data || []);
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [progressData, searchForm, studyProgressData, versionId]);

  // 进页面查询是否导入意图中
  useEffect(() => {
    isUnmount.current = false;
    checkUploading();

    return () => {
      console.log('leave out！！！-----退出>>>>>意图页面');
      clearTimer();
      // 卸载中
      isUnmount.current = true;
    };
  }, [checkUploading]);

  // 进页面查询是否导入意图中
  useEffect(() => {
    isUnmount.current = false;
    checkBatchStudying();

    return () => {
      console.log('leave out！！！-----退出>>>>>意图页面');
      clearTimer();
      // 卸载中
      isUnmount.current = true;
    };
  }, [checkBatchStudying]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    getTableData();
  }, [getTableData]);

  /**
   * 确定操作（导入100%、导入失败）
   * @param versionId
   */
  const handleConfirmUpload = async () => {
    try {
      await confirmUploadIntention(versionId);
      checkUploading();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };
  /**
   * 确定操作（学习100%、导入失败）
   * @param versionId
   */
  const handleConfirmStudy = async () => {
    try {
      await confirmStudyIntention(versionId, 'intention');
      checkBatchStudying();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**开启定时器 */
  function startTimer(type: 'upload' | 'study') {
    if (timer.current) {
      return;
    }
    // 条件：没有定时器，则开启
    // 开启-定时1s刷新-更新进度条
    timer.current = setInterval(() => {
      console.log('1s****定时刷新-进度条');
      type === 'upload' && checkUploading();
      type === 'study' && checkBatchStudying();
    }, 1000);
    console.log('启动定时器', type, timer.current);
  }

  /**清除定时器 */
  function clearTimer() {
    if (!timer.current) {
      return;
    }
    clearInterval(timer.current);
    timer.current = null;
  }

  /**上传成功-用户点击确定*/
  function confirmUpload() {
    handleConfirmUpload();
  }

  /**上传失败-用户点击确定*/
  function cancelUpload() {
    handleConfirmUpload();
  }

  /**学习成功-用户点击确定*/
  function confirmStudy() {
    handleConfirmStudy();
  }

  /**学习失败-用户点击确定*/
  function cancelStudy() {
    handleConfirmStudy();
  }

  /**
   * 翻页、每页条数显示变更
   * @param pageNo 点击页码
   * @param pageSize 点击每页条数
   */
  const onChangePage = (pageNo: number, pageSize?: number) => {
    console.log('搜索条件变更***页码+条数', pageNo, pageSize);
    const data: any = produce(searchForm, (draft: any) => {
      draft.pageNo = pageNo;
      if (pageSize) {
        draft.pageSize = pageSize;
      }
    });
    dispatch(intentionAction.setSearchForm(data));
  };

  /**
   * 搜索条件变更
   * @param text 搜索内容
   */
  const handleSearch = (text: string) => {
    console.log('搜索条件变更***', text);
    const data: any = produce(searchForm, (draft: any) => {
      draft.searchText = text.trim();
      draft.pageNo = 1;
    });
    dispatch(intentionAction.setSearchForm(data));
  };

  /**
   * 对列表数据进行刷新：新增，编辑
   * @param pageNum 最新页码
   */
  const refreshTable = async (newPageNum?: number) => {
    if (newPageNum && newPageNum !== searchForm.pageNo) {
      // 刷新到最新页码
      onChangePage(newPageNum);
    } else {
      // 刷新当前页面
      getTableData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, searchForm.pageNo, searchForm.pageSize);
    refreshTable(newPageNum);
  }

  /**
   * 删除操作
   * @param idx 所删除数据的index
   */
  const handleDelete = (record: IntentionLibraryInfo) => {
    Modal.confirm({
      title: '删除意图提示',
      content: '删除后无法恢复! 确认删除吗?',
      async onOk() {
        try {
          const res = await deleteIntention({
            intentionId: record.intentionId,
          });
          message.success('删除意图成功');
          deleteFresh(1);
          console.log('deleteIntention -> res', res);
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
      },
    });
  };

  /**
   * 点击批量学习按钮
   */
  const handleBatchStudy = async () => {
    try {
      await batchUnderstandByVersion(versionId, 'intention');
      checkBatchStudying();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  // Table列描述数据对象
  const columns: ColumnsType<IntentionLibraryInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      width: 80,
      render: (text, record, index) => index + 1 + searchForm.pageSize * (searchForm.pageNo - 1),
    },
    {
      title: '意图名称',
      dataIndex: 'intentionName',
      key: 'intentionName',
      ellipsis: true,
    },
    {
      title: '扩展问数量',
      dataIndex: 'extendQuestionTotal',
      key: 'extendQuestionTotal',
    },
    {
      title: '未学习/学习失败扩展问数量',
      dataIndex: 'unStudyNumber',
      key: 'unStudyNumber',
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            onClick={() => {
              history.push(
                `/webapp/outbound/ai/robots/version/flow/actions?versionId=${versionId}&intentionId=${
                  intentionList[index].intentionId
                }&intentionName=${encodeURIComponent(intentionList[index].intentionName)}`
              );
            }}
          >
            编辑
          </Button>
          <Button type="link" onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <>
      {/* 1.正常状态：显示列表 */}
      {!progressData && !studyProgressData && (
        <>
          <div className="intention-library-top" style={{ marginTop: 20 }}>
            <Search
              placeholder="请输入意图名称"
              enterButton="搜索"
              defaultValue={searchForm?.searchText}
              style={{ width: 300 }}
              onSearch={handleSearch}
              allowClear
            />
            <Space>
              <Dropdown.Button
                type="primary"
                onClick={() => {
                  history.push(
                    `/webapp/outbound/ai/robots/version/flow/actions?versionId=${versionId}`
                  );
                }}
                overlay={
                  <Menu
                    onClick={({ key }: any) => {
                      if (key === '1') {
                        setUploadVisble(true);
                      } else {
                        commonAiDownload('intention', versionId);
                      }
                    }}
                  >
                    <Menu.Item key="1">导入意图</Menu.Item>
                    <Menu.Item key="2">导出意图</Menu.Item>
                  </Menu>
                }
              >
                新建意图
              </Dropdown.Button>
              <Button type="primary" onClick={debounce(handleBatchStudy, 500)}>
                批量学习
              </Button>
            </Space>
          </div>
          <div style={{ marginTop: 20 }} className="mgr-table">
            <Table
              loading={tableLoading}
              columns={columns}
              dataSource={intentionList}
              rowKey="intentionId"
              pagination={{
                total: total,
                showTotal: (total: number) => `共 ${total} 条`,
                current: searchForm.pageNo,
                pageSize: searchForm.pageSize,
                showSizeChanger: true,
                onChange: onChangePage,
              }}
            />
          </div>
        </>
      )}
      {/* 2.导入状态 */}
      {progressData && (
        <UploadingPic
          progressData={progressData as any}
          callBackFail={cancelUpload}
          callBackSuccess={confirmUpload}
        />
      )}
      {/* 3.批量学习状态 */}
      {studyProgressData && (
        <UploadingPic
          progressData={studyProgressData as any}
          callBackFail={cancelStudy}
          callBackSuccess={confirmStudy}
        />
      )}
      <UploadBatchModal
        show={uploadVisble}
        data={{ versionId: versionId, mode: 'intention' }}
        callback={data => {
          setUploadVisble(false);
          if (data) {
            //  导入意图-接口成功
            checkUploading();
          }
        }}
      />
    </>
  );
};

/**
 * Ai管理菜单模块下，常用的导出函数
 * type类型：
 * intention- 意图
 * question- 问答
 * 文件后缀类型：
 * 0-.xlsx
 * 1-.txt
 */
/**
 *
 * @param mode 类型 'intention' | 'question'
 * @param versionId
 * @param docType 文件类型 0-xlsx，1-txt
 */
export function commonAiDownload(mode: 'intention' | 'question', versionId: number, docType = 0) {
  // 文件类型配置
  const fileConfig = [
    {
      fileDoc: '.xlsx',
      fileWord: 'application/vnd.ms-excel',
    },
    {
      fileDoc: '.txt',
      fileWord: 'text/plain',
    },
  ];
  // 默认是.xlsx类型
  const { fileDoc, fileWord } = fileConfig[docType];

  // 下载模块中英文配置
  const modeName = {
    intention: '意图',
    question: '问答',
  };

  // 批量导出接口
  downloadBatchList(mode, versionId)
    .then(data => {
      console.log(data, '下载');
      if (!data) {
        message.warning('文件下载失败');
        return;
      }
      const timeStr = moment().format('YYYYMMDDHHmmss');
      const fileName = modeName[mode] + timeStr + randomNum(3) + fileDoc;

      if (typeof (window.navigator as any).msSaveBlob !== 'undefined') {
        (window.navigator as any).msSaveBlob(new Blob([data], { type: fileWord }), fileName);
      } else {
        const url = window.URL.createObjectURL(new Blob([data], { type: fileWord }));
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 下载完成移除元素
        window.URL.revokeObjectURL(url); // 释放掉blob对象
      }
    })
    .catch(() => {});
}
